﻿using System.Web;

namespace Anmlz.Services
{
    using System.Globalization;
    using System.Threading;

    using Anmlz.Services.Contracts;

    public static class CultureNames
    {
        public const string English = "en";
        public const string Russian = "ru";
    }

    public class LanguageService : ILanguageService
    {
        private string DefaultCultureTwoLetterName { get; set; }
        private string ForcedRequestCulture { get; set; }
        private const string LanguageSessionKey = "Language";


        public LanguageService()
        {
            DefaultCultureTwoLetterName = CultureNames.Russian;
            this.ForcedRequestCulture = null;
        }

        public void SetCurrentLanguage(string cultureTwoLetterName)
        {
            if (cultureTwoLetterName != CultureNames.English && cultureTwoLetterName != CultureNames.Russian)
            {
                cultureTwoLetterName = DefaultCultureTwoLetterName;
            }

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureTwoLetterName);
            HttpContext.Current.Session[LanguageSessionKey] = cultureTwoLetterName;
        }

        public string GetCurrentLanguage()
        {
            if (this.ForcedRequestCulture != null)
            {
                return ForcedRequestCulture;
            }

            var currentCultureTwoLetterName = HttpContext.Current.Session[LanguageSessionKey];

            if (currentCultureTwoLetterName == null ||
                ((string)currentCultureTwoLetterName != CultureNames.English && (string)currentCultureTwoLetterName != CultureNames.Russian))
            {
                currentCultureTwoLetterName = DefaultCultureTwoLetterName;
            }

            return (string)currentCultureTwoLetterName;
        }

        public void ForceRequestLanguage(string cultureTwoLetterName)
        {
            if (cultureTwoLetterName == CultureNames.English || cultureTwoLetterName == CultureNames.Russian)
            {
                this.ForcedRequestCulture = cultureTwoLetterName;
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureTwoLetterName);
            }
        }

        public void RemoveForcedRequestLanguage()
        {
            if (this.ForcedRequestCulture != null)
            {
                this.ForcedRequestCulture = null;
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(GetCurrentLanguage());   
            }
        }
    }
}
